import mysql.connector as database #Connect to MariaDB
import requests #Module for processing of URL
from bs4 import BeautifulSoup #Module for working with HTML
from datetime import datetime #Get date and time

connection = database.connect(
    user="parcer",
    password="parce",
    host="localhost",
    database="cryptocurrency")

cursor = connection.cursor()

def add_data(name, point, price):
    try:
        table = name.lower()
        statement = f"INSERT INTO {table} (point,price) VALUES (%s, %s)"
        data = (point, price)
        cursor.execute(statement, data)
        connection.commit()
        print("Successfully added entry to database")
    except database.Error as e:
        print(f"Error adding entry to database: {e}")

def get_sources(cryptocyrrency):
    links = []
    try:
        statement = "SELECT cryptocyrrency, rate_link FROM sources WHERE cryptocyrrency=%s"
        data = (cryptocyrrency,)
        cursor.execute(statement, data)
        for (cryptocyrrency, rate_link) in cursor:
            return(rate_link)
    except database.Error as e:
        print(f"Error retrieving entry from database: {e}")

def get_price(link, headers):
    full_page = requests.get(link, headers=headers)
    soup = BeautifulSoup(full_page.content, 'html.parser')
    temp_price = soup.findAll("span", {"class": "pclqee"})
    price = temp_price[0].text
    return(price)

NAMES = ["Bitcoin", "Ethereum", "Monero"]
head = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0'}
now = datetime.now()
datetime = now.strftime("%Y-%m-%d %H:%M:%S")
numbers = [38505.60, 2762.27, 144.88]

for i, name in enumerate(NAMES):
    source = get_sources(name)
    print("Successfully found a link in the database")
    price = get_price(source, head)
    print(f"{name} price: {price} - {datetime}")
    add_data(name, datetime, numbers[i])
    print()

connection.close()
